package com.starblink.android.common.web

import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import android.widget.PopupWindow
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.ext.color
import com.starblink.android.basic.ext.inflater
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.event.TrackEvent
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.FlowCountDownTimer
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.FollowStoreEvent
import com.starblink.android.basic.util.post.CommonMutateManage
import com.starblink.android.common.R
import com.starblink.android.common.databinding.ActivityStoreLinkBinding
import com.starblink.android.common.databinding.ItemWebDealCodeBinding
import com.starblink.android.common.web.deal.WebDealCell
import com.starblink.basic.route.RoutePage
import com.starblink.basic.util.NetWorkUtil
import com.starblink.rocketreserver.fragment.DealVOF

/**
 * 店铺和商品外链框架
 */
abstract class WebShowBackActivity<T : ActivityStoreLinkBinding, VM : BaseViewModel> :
    GuangWebBaseActivity<T, VM>() {

    @Autowired(name = RoutePage.Product.PRODUCT_ID)
    @JvmField
    var productId: String? = null//商品id

    @Autowired(name = RoutePage.Store.URL)
    @JvmField
    var mWeburl: String = ""

    @Autowired(name = RoutePage.Store.STORE_ID)
    @JvmField
    var storeId: String? = null//店铺id

    @Autowired(name = RoutePage.Store.SUB_OR_NOT)
    @JvmField
    var subOrNot: Boolean = false//店铺订阅状态

    @Autowired(name = RoutePage.Store.STORE_NAME)
    @JvmField
    var storeName: String? = null

    @Autowired(name = RoutePage.Store.STORE_LOGO)
    @JvmField
    var storeLogo: String? = null

    @JvmField
    @Autowired(name = RoutePage.Web.ARG_USECACHE)
    var ifUseCache: Boolean = true

    private var ifNeedClearCache = false //是否需要清理缓存

    var dealList: List<DealVOF> = emptyList()

    var pageDef: Int = SpmPageDef.ProductDetailWebView

    val adapter: MutableAdapter by lazyOnNone {
        MutableAdapter(dealList).apply {
            addVhDelegate {
                WebDealCell(ItemWebDealCodeBinding.inflate(it.inflater, it, false)) {
                    ifShowCode = false
                    changeState()
                }
            }
        }
    }

    override fun initData() {
        super.initData()
        setStatusBarBlackText()
        setPageEnf()
        initWebView(
            viewGroup = viewBinding.flContent,
            pbWebViewBar = viewBinding.pbWebView,
            mWebUrl = mWeburl,
            ifUseCache = ifUseCache
        )
        if (intent.hasExtra(RoutePage.Store.SUB_OR_NOT)) {
            subOrNot = intent.getBooleanExtra(RoutePage.Store.SUB_OR_NOT, false)
        }

        setView()
        setListener()
        //同步订阅数据
        FlowBus.with<FollowStoreEvent>(FlowConst.FOLLOW_STORE_EVENT).register(this) {
            if (it.id != null && it.id == storeId && it.followed != subOrNot) {
                subOrNot = it.followed
                followStore(subOrNot)
            }
        }

    }

    open fun trackView() {
        //关闭埋点
        viewBinding.rlTop.ivClose.trackData(
            pageDef,
            SpmElementDef.ProductLinkPageBack,
            onlyHit = true
        )
        //分享埋点
        viewBinding.rlTop.ivWeb.trackData(
            pageDef,
            SpmElementDef.ShareClickSpm,
            onlyHit = true,
            params = trackParams()
        )
        viewBinding.rlTop.ivFresh.trackData(
            pageDef,
            SpmElementDef.ReloadWebSpm,
            onlyHit = true,
            params = trackParams()
        )
        viewBinding.rlBottom.llOpenStore.trackData(
            page = pageDef,
            element = SpmElementDef.ProductLinkPageOpen, onlyHit = true,
            params = trackParams()
        )
        viewBinding.rlTop.ivFresh.setOnClickListener {
            //刷新商品
            showLoadingAnim(true)
            mWebView.guangLoadUrl(mWeburl, ifUseCache)
        }

    }

    fun setView() {
        followStore(subOrNot)
//        funWebDialog?.let {
//            //是否有店铺信息 没有店铺信息时兜底 隐藏follow
//            it.rlFollowStore.visibleOrGone(!CheckUtil.isEmpty(storeName))
//            it.viewFollowStore.visibleOrGone(!CheckUtil.isEmpty(storeName))
//        }
    }

    private var ifShowCode = false //显示 couponcode

    private var popupWindow: PopupWindow? = null
    private fun setListener() {
        viewBinding.recyclerView.layoutManager = LinearLayoutManager(this)
        viewBinding.recyclerView.setHasFixedSize(true)
        viewBinding.recyclerView.itemAnimator = null

        viewBinding.rlTop.ivClose.setOnClickListener {
            finish()
        }

        viewBinding.rlBottom.ivBack.setOnClickListener {
            if (mWebView.canGoBack()) {
                mWebView.goBack()
                setWebBackStateView()
            } else {
                finish()
            }
        }
        viewBinding.rlBottom.ivNext.setOnClickListener {
            if (mWebView.canGoForward()) {
                mWebView.goForward()
                setWebBackStateView()
            }
        }
    }

    private fun followStore(subOrNot: Boolean) {
//        viewBinding.rlBottom.ivFollow.setImageResource(if (subOrNot) R.mipmap.icon_web_followed else R.mipmap.icon_web_follow)
//        funWebDialog?.followStore(subOrNot)
    }

    fun clickFollowStore(view: View) {
        storeId?.let { it1 ->
            CommonMutateManage.subscribeOrNotMerchant(
                mContext,
                it1,
                storeName ?: "",
                subOrNot,
                lifecycleScope,
                refreshState = {
//                        followStore(!subOrNot)
                },
                resultCallback = { result ->
                    if (result) {
                        subOrNot = !subOrNot
                        followStore(subOrNot)
                        view.trackData(
                            page = pageDef,
                            element = SpmElementDef.StoreSub, onlyHit = true,
                            params = mapOf(
                                "merchantName" to (storeName ?: ""),
                            )
                                .plus("status" to (if (UserDataCenter.isLogin()) "1" else "0"))
                                .plus("result" to if (subOrNot) "0" else "1")
                        )
                    }
                })
        }
    }

    //刷新link动态返回状态
    private fun setWebBackStateView() {
        FlowCountDownTimer(time = 1).start(callBack = {
        }, onFinish = {
            if (mWebView.canGoForward()) {
                viewBinding.rlBottom.ivNext.setImageResource(R.mipmap.icon_web_next)
            } else {
                viewBinding.rlBottom.ivNext.setImageResource(R.mipmap.icon_web_next_not)
            }
            //1.4.0 修改回退一直高亮状态
//            if (mWebView.canGoBack()) {
//                viewBinding.rlBottom.ivBack.setImageResource(R.mipmap.icon_web_back)
//            } else {
//                viewBinding.rlBottom.ivBack.setImageResource(R.mipmap.icon_web_back_not)
//            }
            viewBinding.rlBottom.ivBack.setImageResource(R.mipmap.icon_web_back)
        })
    }

    //start---GuangWebView.OnWebChangeListener
    override fun onInnerLinkChecked() {
        setWebBackStateView()
    }

    override fun onWebLoadFinish(url: String?) {
        super.onWebLoadFinish(url)
        setWebBackStateView()
    }
    //end---GuangWebView.OnWebChangeListener

    /**
     * 集成了系统的回退和网页的回退
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
            mWebView.goBack()

            setWebBackStateView()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }


    override fun onNetworkConnectionChanged(
        isConnected: Boolean,
        networkType: NetWorkUtil.NetworkType?
    ) {
    }


    /**
     * 显示底部按钮
     */
    fun showBottomView() {
        viewBinding.rlBottom.btnMore.visibleOrGone(true)
        viewBinding.rlBottom.llStoreBot.visibleOrGone(true)
        viewBinding.rlBottom.llConpun.visibleOrGone(!dealList.isNullOrEmpty()) {
            viewBinding.recyclerView.adapter = adapter
            showDiscountView()
        }
    }

    /**
     * 展示deal弹窗
     */
    private fun showDiscountView() {

        viewBinding.rlBottom.llConpun.setOnClickListener {
            //是否显示功能按x钮
            ifShowCode = !ifShowCode
            changeState()
        }
    }

    private fun changeState() {
        if (!dealList.isNullOrEmpty()) {
            //向上位移显示动画  从自身位置的最下端向上滑动了自身的高度
            val translateAniShow = TranslateAnimation(
                Animation.RELATIVE_TO_SELF,  //RELATIVE_TO_SELF表示操作自身
                0f,  //fromXValue表示开始的X轴位置
                Animation.RELATIVE_TO_SELF,
                0f,  //fromXValue表示结束的X轴位置
                Animation.RELATIVE_TO_SELF,
                1f,  //fromXValue表示开始的Y轴位置
                Animation.RELATIVE_TO_SELF,
                0f
            ) //fromXValue表示结束的Y轴位置
            translateAniShow.repeatMode = Animation.REVERSE
            translateAniShow.duration = 500

            //向下位移隐藏动画  从自身位置的最上端向下滑动了自身的高度
            val translateAniHide = TranslateAnimation(
                Animation.RELATIVE_TO_SELF,  //RELATIVE_TO_SELF表示操作自身
                0f,  //fromXValue表示开始的X轴位置
                Animation.RELATIVE_TO_SELF,
                0f,  //fromXValue表示结束的X轴位置
                Animation.RELATIVE_TO_SELF,
                0f,  //fromXValue表示开始的Y轴位置
                Animation.RELATIVE_TO_SELF,
                1f
            ) //fromXValue表示结束的Y轴位置
            translateAniHide.repeatMode = Animation.REVERSE
            translateAniHide.duration = 500

            viewBinding.rlBottom.ivDeals.setImageResource(if (this.ifShowCode) R.mipmap.icon_web_deal2 else R.mipmap.icon_web_deal)
            viewBinding.rlBottom.llConpun.setBackgroundColor(color(if (this.ifShowCode) com.starblink.basic.style.R.color.tag_yellow_1 else com.starblink.basic.style.R.color.tag_yellow_2))
            if (this.ifShowCode) {
                viewBinding.llShopCode.startAnimation(translateAniShow)
                viewBinding.llShopCode.visibility = View.VISIBLE
                viewBinding.lineDeal.visibility = View.VISIBLE

                SpmTrackHandler.addSingleTrackData(
                    SkAntEntity(
                        event = TrackEvent.elementExposure.value,
                        spmCnt = GTrackerAssistUtils.fetchElementValue(
                            pageDef, SpmElementDef.StoreWebCouponSpm
                        ),
                        params = trackParams()
                    )
                )
            } else {
                viewBinding.llShopCode.startAnimation(translateAniHide)
                translateAniHide.setAnimationListener(object : Animation.AnimationListener {
                    override fun onAnimationStart(animation: Animation) {}
                    override fun onAnimationEnd(animation: Animation) {
                        viewBinding.llShopCode.visibility = View.INVISIBLE
                        viewBinding.lineDeal.visibility = View.INVISIBLE
                    }

                    override fun onAnimationRepeat(animation: Animation) {}
                })
            }
        }
    }

    abstract fun setPageEnf()

    //    abstract fun changeShowFunBtn(ifShowFunBtn: Boolean)
//    abstract fun clickFunShare()
    abstract fun trackParams(): Map<String, String>

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (popupWindow != null && popupWindow!!.isShowing) {
            return false
        }
        return super.dispatchTouchEvent(ev)
    }
}
